import React, { useCallback, useEffect, useRef, useState } from 'react';
import { ScrollHead, TabsH, ObserverText } from "../../components";
import { postRankingsList, postRankingsTitleList } from "../../services";
import RankChildren from "./RankChildren";
import Header from "./Header";
import { View, TouchableOpacity, StyleSheet } from "react-native";
import { dpw10, dpw208, dpw24, dpw48, dpw92 } from "../../constants";
import { useTableReducer } from "../../hooks";

const list = [
    { Id: 'head' },
    { Id: 'context' },
]

const StickyHeader = ({ titles, changePid, actId, isFix }: any) => {
    
    const onPress = (id: number) => {
        if (id !== actId) {
            changePid(id)
        }
    }
    
    return (
        <View style={{ position: 'relative', height: isFix ? 1 : 0 }}>
            <View style={{...styles.titles, top: (isFix ? dpw48 : dpw208) + dpw10, }}>
                {Array.isArray(titles) ? titles.map((it, i) => (
                    <TouchableOpacity key={it.Id || i} onPress={() => onPress(it.Id)} style={styles.title}>
                        <ObserverText style={{paddingHorizontal: dpw10, textAlign: 'center', width: '100%'}} isActive={actId === it.Id} tKey={`${it.Title || ''}`.trim()} type="tab-title-h" />
                    </TouchableOpacity>
                )) : null}
            </View>
        </View>
)
};
 
interface TitleProps {
    Describe:string
    DetailImage:string
    IconImage:string
    Id:number
    Title:string
    Type:number
}
const Rank = (props: any) => {
    const { navigation, route } = props
    const { rankId, typeId } = route.params || {}
    const [titles, setTitles] = useState<TitleProps[]>([])
    const [{ classTitle, firstName, firstUrl }, setData] = useState<Record<string, string>>({})
    const [pId, setPId] = useState()
    const [isFix, setIsFix] = useState(false)
     const [{ data, total, loading, pageIndex }, dispatch] = useTableReducer({
        total: 0,
        data: [],
        pageIndex: 1,
        pageSize: 10,
        loading: false,
    });
    
    const getData = useCallback(({ rankId, index, isMore }: any) => {
        if (!titles) return
        dispatch({ type: 'init' })
        postRankingsList({ RankId: rankId, pageIndex: index, pageSize: 10 })
            .then((res: any) => {
                if (!Array.isArray(res?.Data)) {
                    dispatch({ type: 'error' });
                } else {
                    dispatch({
                        type: 'success',
                        payload: {
                            data: isMore ? (preD: any[]) => [...preD, ...res.Data] : res.Data,
                            total: res?.Count,
                            pageIndex: index,
                        },
                    });
                    if (!isMore) {
                        setData({
                            classTitle: titles.find((it) => it.Id === rankId)?.Title || '',
                            firstName: res?.Data?.[0]?.Title,
                            firstUrl: res?.Data?.[0]?.ExtensionUrl
                        })
                    }
                }
            })
            .catch(() => {
                dispatch({ type: 'error' });
            })
            .finally(() => {
                // fincb && fincb();
            });
    }, [dispatch, titles]);
    
    const onLoadMore = () => {
        if (!loading && total && total > data.length) {
            getData({ rankId: pId, index: pageIndex + 1, isMore: true })
        }
    }
    
    useEffect(() => {
        if (pId) {
            getData({ rankId: pId, index: 1 });
        }
    }, [pId]);
    
    const onFixed = (d: number) => {
        if (!isFix && d > 1.5) {
            setIsFix(true)
        } else if (isFix && d <= 1.5) {
            setIsFix(false)
        }
    }
    
    useEffect(() => {
        postRankingsTitleList({ Type: typeId || 1 })
            .then((res: any) => {
                if (Array.isArray(res?.Data)) {
                    setTitles(res?.Data)
                    setPId(rankId || res?.Data[0]?.Id)
                } else {
                    throw new Error("");
                }
            })
            .catch(() => { })
    }, [typeId, rankId])
    
    const _renderItem = ({ item }: any) => {
        if (item.Id === 'head') {
            return <Header classTitle={classTitle} firstName={firstName} firstUrl={firstUrl} />
        }
        return (
            <TabsH isFixed titles={titles} pId={pId}>
                <RankChildren data={data as any[]} navigation={navigation} />
            </TabsH>
        )
    }
    
    return (
        <ScrollHead
            title="rankTitle"
            navigation={navigation}
            data={list}
            listerTop={onFixed}
            renderItem={_renderItem}
            ListHeaderComponent={<StickyHeader isFix={isFix} actId={pId} titles={titles} changePid={setPId} />}
            stickyHeaderIndices={[0]}
            onEndReached={onLoadMore}
        />
    );
};
 
export default Rank;

const styles = StyleSheet.create({
    titles: {
        flexDirection: 'column',
        flex: 1,
        width: dpw92,
        position: 'absolute',
        left: 0,
        zIndex: 10
    },
    title: {
        marginBottom: dpw10,
        borderTopRightRadius: dpw24,
        borderBottomRightRadius: dpw24,
        overflow: 'hidden',
        backgroundColor: 'pink'
    },
})